package com.lvyq.myplayer.common.util

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.Settings
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.lvyq.myplayer.R

/**
 * 文件描述：ManifestUtils 动态权限申请封装
 * 作者：lvyq
 * 创建时间：2025-05-27
 * 修改时间：2025-05-27
 */
open class ManifestUtils {



    /**
     * 检测读写权限
     */
    companion object {
        //存储权限
        val REQUEST_LEGACY_STORAGE = 1
        val REQUEST_INSTALL_APP = 2


        /**
         *存储权限
         */
        open fun checkStoragePermission(activity: AppCompatActivity) :Boolean{
            var next:Boolean=true
            when {
                //TODO Android 13+ 需单独申请媒体文件权限（READ_MEDIA_IMAGES等），
                //兼容 Android 11+ 。需手动授权 -全局权限
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
                    if (!Environment.isExternalStorageManager()) {
                        next=false
                        try {
                            //全局设置页
                           /* val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)
                            activity.startActivityIfNeeded(intent,REQUEST_LEGACY_STORAGE)*/
                            // 跳转应用详情页
                            AlertDialog.Builder(activity)
                                .setTitle("存储权限请求")
                                .setMessage("用于版本升级、歌曲下载、边存边听功能")
                                .setPositiveButton("去设置") { _, _ ->
                                    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                                        data = Uri.parse("package:${activity.packageName}")
                                    }
                                    activity.startActivityIfNeeded(intent,REQUEST_LEGACY_STORAGE)
                                }.show()
                        } catch (e: Exception) {
                            // 备用跳转方案
                            val intent = Intent(Settings.ACTION_SETTINGS)
                            activity.startActivity(intent)
                        }

                    }
                }
                //兼容 Android 6+
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> {
                    val permissions = arrayOf(
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    )
                    if (permissions.any {
                            ActivityCompat.checkSelfPermission(activity, it) != PackageManager.PERMISSION_GRANTED
                        }) {
                        next=false
                        // 跳转应用详情页
                        AlertDialog.Builder(activity)
                            .setTitle("存储权限请求")
                            .setMessage("用于版本升级、歌曲下载、边存边听功能")
                            .setPositiveButton("去设置") { _, _ ->
                       val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                            data = Uri.parse("package:${activity.packageName}")
                        }
                        activity.startActivityIfNeeded(intent,REQUEST_LEGACY_STORAGE)
                        }.show()
                        //弹框开启权限
                      //  ActivityCompat.requestPermissions(activity, permissions, REQUEST_LEGACY_STORAGE)
                    }
                }
                else -> {
                    // Android 6.0以下默认有存储权限
                }
            }

            return next
        }

        /**
         * 安装应用权限
         */

        fun checkInstallAPPPermission(activity: AppCompatActivity) :Boolean{
            var next:Boolean=true
            // 检查安装权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !activity.packageManager.canRequestPackageInstalls()) {
                try {
                    next=false
                    AlertDialog.Builder(activity)
                        .setTitle("安装权限请求")
                        .setMessage("请开启安装未知应用权限")
                        .setPositiveButton("去设置") {  _, _ ->
                            /*val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
                            activity.startActivityIfNeeded(intent,REQUEST_INSTALL_APP)*/
                            val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).apply {
                                data = Uri.parse("package:${activity.packageName}")
                            }
                            activity.startActivityIfNeeded(intent,REQUEST_INSTALL_APP)
                        }.show()
                } catch (e: Exception) {
                    // 备用跳转方案
                    val intent = Intent(Settings.ACTION_SETTINGS)
                    activity.startActivity(intent)
                }
            }
            return next
        }

    }
}